"""
数据源字段管理API路由
"""
from typing import List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from database import get_db
from utils.dependencies import get_current_active_user
from models.user import User
from schemas.data_source_field import (
    DataSourceField,
    DataSourceFieldUpdate,
    DataSourceFieldAnalysis,
    DataSourceDataPreview,
    DataSourceQuery
)
from services.data_source_field_service import DataSourceFieldService

router = APIRouter(prefix="/api/data-sources", tags=["数据源字段"])


@router.get("/{data_source_id}/tables/{table_name}/fields")
async def get_table_fields(
    data_source_id: int,
    table_name: str,
    identify_types: bool = Query(False, description="是否识别字段类型"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """实时获取指定表的字段列表"""
    try:
        return DataSourceFieldService.get_table_fields(db, data_source_id, table_name, current_user.id, identify_types)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取字段失败: {str(e)}")


@router.get("/{data_source_id}/fields", response_model=List[DataSourceField])
async def get_data_source_fields(
    data_source_id: int,
    table_name: str = Query(None, description="表名（可选，用于兼容旧接口）"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取数据源字段列表（兼容接口，建议使用新的表字段接口）"""
    try:
        if table_name:
            return DataSourceFieldService.get_table_fields(db, data_source_id, table_name, current_user.id, False)
        else:
            return DataSourceFieldService.get_data_source_fields(db, data_source_id, current_user.id)
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取字段失败: {str(e)}")


@router.put("/fields/{field_id}", response_model=DataSourceField)
async def update_data_source_field(
    field_id: int,
    field_update: DataSourceFieldUpdate,
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """更新数据源字段"""
    try:
        return DataSourceFieldService.update_field(db, field_id, field_update, 1)  # 暂时使用用户ID=1
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新字段失败: {str(e)}")


@router.post("/{data_source_id}/query", response_model=DataSourceDataPreview)
async def query_data_source_data(
    data_source_id: int,
    query: DataSourceQuery,
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """查询数据源数据"""
    # 设置数据源ID
    query.data_source_id = data_source_id

    try:
        return DataSourceFieldService.query_data_source_data(db, query, 1)  # 暂时使用用户ID=1
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询数据失败: {str(e)}")


@router.get("/{data_source_id}/preview", response_model=DataSourceDataPreview)
async def preview_data_source_data(
    data_source_id: int,
    limit: int = 10,
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """预览数据源数据"""
    query = DataSourceQuery(
        data_source_id=data_source_id,
        limit=limit,
        offset=0
    )

    try:
        return DataSourceFieldService.query_data_source_data(db, query, 1)  # 暂时使用用户ID=1
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"预览数据失败: {str(e)}")
